package com.zhang.sql;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import static org.apache.flink.table.api.Expressions.$;

/**
 * @title: 自定义UDF函数
 * @author: zhang
 * @date: 2022/2/15 21:00
 */
public class FlinkSQL_UDAF {
    public static void main(String[] args) throws Exception {
        //todo 获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        SingleOutputStreamOperator<Long> source = env.socketTextStream("localhost", 9999)
                .map(new MapFunction<String, Long>() {
                    @Override
                    public Long map(String value) throws Exception {
                        return Long.parseLong(value);
                    }
                });

        // 流转表
        Table table = tableEnv.fromDataStream(source, $("num"));

        //注册自定义函数
        tableEnv.createTemporaryFunction("MaxInt", MaxFunc_UDAF.class);

        //flinkSQL方式使用函数
        tableEnv.sqlQuery("select MaxInt(num) from " + table).execute().print();

        //todo 执行任务
        env.execute();
    }
}
